package api

import (
	"github.com/gin-gonic/gin"
	"github.com/gorilla/websocket"
	log "github.com/sirupsen/logrus"
	"lib/http"
	http2 "net/http"
	"strconv"
	"sync"
	"vap/daemon/gua"
	"vap/global"
)

var guacdTunnelMap sync.Map

func (api guaApi) VNC(c *gin.Context) {
	in := struct {
		Id       string `form:"id"`
		Width    string `form:"width"`
		Height   string `form:"height"`
		Account  string `form:"account"`
		Password string `form:"password"`
		Ip       string `form:"ip"`
		Port     int    `form:"port"`
	}{}
	if err := c.ShouldBindQuery(&in); err != nil {
		http.BadWithParamsError(c, err)
		return
	}
	var UpGrader = websocket.Upgrader{
		CheckOrigin: func(r *http2.Request) bool {
			return true
		},
		// 在原始websocket中添加对guacamole协议的支持
		Subprotocols: []string{"guacamole"},
	}
	ws, err := UpGrader.Upgrade(c.Writer, c.Request, nil)
	if err != nil {
		http.BadWithErr(c, err)
		return
	}
	configuration := setConfig(in.Width, in.Height, in.Account, in.Password, in.Ip, strconv.Itoa(in.Port))
	guacdTunnel, err := gua.NewTunnel(global.Conf.GuacdAddr, configuration)
	if err != nil {
		http.BadWithErr(c, err)
		return
	}
	guacdTunnelMap.Store(in.Id, guacdTunnel)
	guacamoleHandler := gua.NewGuacamoleHandler(ws, guacdTunnel)
	guacamoleHandler.Start()
	for {
		var message []byte
		_, message, err = ws.ReadMessage()
		if err != nil {
			guacamoleHandler.Stop()
			return
		}
		log.Println(string(message))
		_, err = guacdTunnel.WriteAndFlush(message)
		if err != nil {
			return
		}
	}
}

func setConfig(width, height, account, pwd, ip, port string) (configuration *gua.Configuration) {
	configuration = gua.NewConfiguration()
	configuration.Protocol = "vnc"
	configuration.SetParameter("width", width)
	configuration.SetParameter("height", height)
	configuration.SetParameter("password", pwd)
	configuration.SetParameter("hostname", ip)
	configuration.SetParameter("port", port)
	return
}
